import axios from 'axios';
import { Message } from 'element-ui';
import { Loading } from 'element-ui';
import store from '@/store';
import { getToken } from '@/utils/auth';
import router from '@/router';
// const COMMON_API = ['sysDict', 'sysDictType', 'sysDynamicText'];
let requestCount = 0;
let loadingInstance = null;
// create an axios instance
const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
	timeout: 30000 // request timeout
});
// request interceptor
service.interceptors.request.use(
	config => {
		// const regex = /\/([^\/]+)\//;
		// const match = regex.exec(config.url);
		// if (COMMON_API.includes(match[1])) {
		// 	config.baseURL = process.env.VUE_APP_COMMON_BASE_API;
		// }
		// config.baseURL = "/123333"
		config.headers['request-startTime'] = new Date().getTime();
		// config.headers['type'] = 'market';
		// do something before request is sent
		// console.log(config, 'config')
		if (requestCount === 0) {
			loadingInstance = Loading.service({
				// 是否全屏
				// fullscreen:false,
				lock: true,
				target: document.querySelector('.base-popup-content'),
				text: '正在加载',
				background: 'rgba(0,0,0,0.2)'
			});
		}
		// 每次请求计数+1
		requestCount += 1;
		if (store.getters.token) {
			config.headers.token = getToken();
		}
		return config;
	},
	error => {
		console.log('errpr1');
		requestCount -= 1;
		// 当加载实例存在且计数小于等于0的时候把加载效果关闭
		if (requestCount <= 0 && loadingInstance) {
			requestCount = 0;
			loadingInstance.close();
		}
		return Promise.reject(error);
	}
);
service.interceptors.response.use(
	async response => {
		// console.log('errpr2')
		const { data, statusText, status } = response; // 默认json格式
		// console.log(status, 'status')
		if (status === 200) {
			// 当请求返回的时候计数-1
			requestCount -= 1;
			// dialog401Count = 0
			// 当加载实例存在且计数小于等于0的时候把加载效果关闭
			if (requestCount <= 0 && loadingInstance) {
				requestCount = 0;
				loadingInstance.close();
			}
			if (data instanceof Blob) {
				return response;
			}
			if (Object.prototype.toString.call(data) === '[object Object]' && data?.code !== 200 && requestCount <= 0) {
				console.log('4444444');
				if (data?.code === 401) {
					Message({ type: 'error', message: '登录超时，请重新登录' });
					// 退出登录
					await store.dispatch('user/removeUserInfo');
					// 跳转回登录页面
					router.push('/login');
					// 中止程序
					return Promise.reject(new Error(statusText));
				} else {
					// if (Object.prototype.toString.call(data) === '[object Object]') {
					Message({ type: 'error', message: data.message });
					// }
				}
			}

			return data;
		} else {
			Message({ type: 'error', statusText });
			// codeErrorHandle(data)
			return Promise.reject(new Error(statusText));
		}
	},
	async error => {
		// console.log('errpr3')
		// const { status } = error.response
		requestCount -= 1;
		// 当加载实例存在且计数小于等于0的时候把加载效果关闭
		if (requestCount <= 0 && loadingInstance) {
			requestCount = 0;
			loadingInstance.close();
			Message({ type: 'error', message: error.message });
		}
		if (error.message.includes('timeout')) {
			// 判断请求异常信息中是否含有超时timeout字符串
			// console.log(error, '111')
			router.replace({
				name: 'error_500'
			});
			// console.log('timeout')
			return Promise.reject(error); // reject这个错误信息
		}
		if (error.message.includes('500')) {
			// 判断请求异常信息中是否含有超时timeout字符串
			console.log('1112222222');
			router.push({
				name: 'error_500'
			});
			// console.log('timeout')
			return Promise.reject(error); // reject这个错误信息
		}
		if (error.message.includes('Network Error')) {
			// 判断请求异常信息中是否含有超时timeout字符串
			// console.log(error, '111')
			router.replace({
				name: 'networkError'
			});
			// console.log('timeout')
			return Promise.reject(error); // reject这个错误信息
		}
		// 把错误消息提示给用户
		// 处理token失效的问题
		// 发现401的时候，退出登录，清空token和用户信息，提示用户重新登录
		// console.log(error, 'error')
		return Promise.reject(error);
		// 中止程序执行
	}
);

export default service;
